package flc.ast.activity;

import androidx.appcompat.app.AppCompatActivity;

import android.app.Dialog;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.RectF;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;

import com.blankj.utilcode.util.ImageUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.stark.imgedit.view.imagezoom.ImageViewTouchBase;

import flc.ast.BaseAc;
import flc.ast.HomeActivity;
import flc.ast.R;
import flc.ast.databinding.ActivityPicRotateBinding;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.basic.utils.RxUtil;

public class PicRotateActivity extends BaseAc<ActivityPicRotateBinding> {

    public static String imgPath = "";
    private Bitmap mImgBitmap;
    private int currentAngel = 0;
    private Dialog myTipDialog;

    @Override
    protected int onCreate() {
        return R.layout.activity_pic_rotate;
    }

    @Override
    public void onBackPressed() {
        myTipDialog.show();
    }

    @Override
    protected void initView() {
        mDataBinding.ivPicRotateBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        mDataBinding.ivRotateSave.setOnClickListener(this);
        mDataBinding.ivPicRotate90.setOnClickListener(this);
        mDataBinding.ivPicRotateHorizontal.setOnClickListener(this);
        mDataBinding.ivPicRotateVertical.setOnClickListener(this);
        //提示弹框
        tipDialog();
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()){
            case R.id.ivRotateSave://保存
                saveImgRotate();
                break;
            case R.id.ivPicRotate90://90度
                currentAngel += 90;
                if (currentAngel == 360) {
                    currentAngel = 0;
                } else if (currentAngel == 0) {
                    currentAngel = 360;
                }
                rotateImg();
                break;
            case R.id.ivPicRotateHorizontal://水平
                currentAngel += 180;
                rotateImg();
                mDataBinding.myRotateView.mirrorUD(currentAngel);
                break;
            case R.id.ivPicRotateVertical://垂直
                currentAngel += 180;
                rotateImg();
                mDataBinding.myRotateView.mirrorLR(currentAngel);
                break;
            //提示弹框
            case R.id.ivDialogTipCancel://取消
                myTipDialog.dismiss();
                break;
            case R.id.ivDialogTipRight://确定
                myTipDialog.dismiss();
                finish();
                break;
        }
    }

    @Override
    protected void initData() {
        if (TextUtils.isEmpty(imgPath)) return;
        mImgBitmap = ImageUtils.getBitmap(imgPath);
        mDataBinding.imageViewTouch.setImageBitmap(mImgBitmap);
        mDataBinding.imageViewTouch.setDisplayType(ImageViewTouchBase.DisplayType.FIT_TO_SCREEN);
        mDataBinding.imageViewTouch.setScaleEnabled(false);// 禁用缩放
        mDataBinding.imageViewTouch.post(new Runnable() {
            @Override
            public void run() {
                RectF bitmapRect = mDataBinding.imageViewTouch.getBitmapRect();
                mDataBinding.myRotateView.addBit(mImgBitmap, bitmapRect);
            }
        });
        //设置进度条
        mDataBinding.sbRotate.setMax(360);
        mDataBinding.sbRotate.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                currentAngel = seekBar.getProgress();
                rotateImg();
            }
        });
    }

    //旋转图片
    private void rotateImg() {
        mDataBinding.imageViewTouch.setVisibility(View.GONE);
        mDataBinding.myRotateView.setVisibility(View.VISIBLE);
        mDataBinding.myRotateView.rotateImage(currentAngel);
    }

    //保存图片旋转
    private void saveImgRotate() {
        showDialog(getString(R.string.save_ing));
        RxUtil.create(new RxUtil.Callback<Bitmap>() {
            @Override
            public void doBackground(ObservableEmitter<Bitmap> emitter) {
                RectF imageRect = mDataBinding.myRotateView.getImageNewRect();
                Bitmap originBit = Bitmap.createBitmap(mImgBitmap).copy(Bitmap.Config.ARGB_8888, true);
                Bitmap result = Bitmap.createBitmap((int) imageRect.width(), (int) imageRect.height(), Bitmap.Config.ARGB_8888);
                Canvas canvas = new Canvas(result);
                int w = originBit.getWidth() >> 1;
                int h = originBit.getHeight() >> 1;
                float centerX = imageRect.width() / 2;
                float centerY = imageRect.height() / 2;

                float left = centerX - w;
                float top = centerY - h;

                RectF dst = new RectF(left, top, left + originBit.getWidth(), top + originBit.getHeight());
                canvas.save();
                //bug fixed  应用时不需要考虑图片缩放问题 重新加载图片时 缩放控件会自动填充屏幕
                canvas.scale(mDataBinding.myRotateView.getScaleX(), mDataBinding.myRotateView.getScaleY(), imageRect.width() / 2, imageRect.height() / 2);
                canvas.rotate(mDataBinding.myRotateView.getRotateAngle(), imageRect.width() / 2, imageRect.height() / 2);

                canvas.drawBitmap(originBit, new Rect(0, 0, originBit.getWidth(), originBit.getHeight()), dst, null);
                canvas.restore();
                //保存到相册
                ImageUtils.save2Album(result, Bitmap.CompressFormat.PNG);
                emitter.onNext(result);
            }

            @Override
            public void accept(Bitmap bitmap) {
                dismissDialog();
                ToastUtils.showShort(R.string.save_suc);
                startActivity(HomeActivity.class);
            }
        });
    }

    //提示弹框
    private void tipDialog() {
        myTipDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_tip, null);
        myTipDialog.setContentView(inflate);
        myTipDialog.setCancelable(true);
        Window dialogWindow = myTipDialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.BOTTOM);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 0.9);
        lp.y = 50;
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        ImageView cancel = inflate.findViewById(R.id.ivDialogTipCancel);
        ImageView right = inflate.findViewById(R.id.ivDialogTipRight);
        TextView textView=inflate.findViewById(R.id.tvDialogTipText);
        textView.setText(getString(R.string.image_not_save));
        cancel.setOnClickListener(this);
        right.setOnClickListener(this);
    }

}